﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KagSharp.Expressions
{
    public class IfExpression : TagExpression
    {
    	private IdentifierExpression _Condition;
    	public IdentifierExpression Condition { get{return _Condition;}set{_Condition=value;} }
        private List<IExpression> _Children;
        public List<IExpression> Children { get{return _Children;} set{_Children=value;} }
        private IfExpression _Fallback;
        public IfExpression Fallback { get{return _Fallback;}set{_Fallback=value;} }
        private bool _IsRoot;
        public bool IsRoot { get{return _IsRoot;}set{_IsRoot=value;} }

        public IfExpression(
            string tagName, List<IExpression> parameters,
            List<IExpression> children, IfExpression fallback)
            : base(tagName, parameters)
        {
            IsRoot = tagName == "if";
            Children = children;
            Fallback = fallback;
            Condition = null;
            foreach (IExpression p in parameters)
            {
            	if (p is ParameterExpression)
            	{
            		ParameterExpression p2 = (ParameterExpression)p;
            		if (p2.Name == "exp")
            		{
            			Condition = p2.Value as IdentifierExpression;
            			break;
            		}
            	}
            }
            /*
            Condition = parameters
                .Where(p => p is ParameterExpression)
                .Cast<ParameterExpression>()
                .FirstOrDefault(p => p.Name == "exp")?
                .Value as IdentifierExpression;*/
        }

        public override void Print(StringBuilder sb, bool verbose, int indentLevel)
        {
            ExpressionHelper.Indent(sb, GetType(), indentLevel);
            sb.Append("[").Append(IsRoot ? "if" : (Condition != null ? "elsif" : "else"));
            if (Parameters != null && Parameters.Count > 0)
            {
                sb.Append(' ');
                ExpressionHelper.PrintDelimited(sb, Parameters, " ", verbose);
            }
            sb.Append("]");
            ExpressionHelper.PrintDelimited(sb, Children, "", verbose, ++indentLevel);
            indentLevel--;
            if (Fallback != null) Fallback.Print(sb, verbose, indentLevel);
            if (IsRoot)
            {
                ExpressionHelper.Indent(sb, GetType(), indentLevel);
                sb.Append("[endif]");
            }
        }

        public override TR Accept<TR>(IExpressionVisitor<TR> visitor, string context) {
        	return visitor.Visit(this, context);}

        public override Type ValueType {get{return typeof(TagExpression);}}

        public override string ToString() {return "IfExpression: " + Condition;}
    }
}
